using System;
using System.Collections.Generic;
using System.Text;
using SqlTools.DataAccessLibrary;
using System.Data;
using SqlTools.SampleDAL.Data;

namespace SqlTools.SampleDAL
{
	public partial class User : BusinessObject, IDbObject<UserPrimaryKey>
	{
		protected UserPrimaryKey _userPrimaryKey;
		protected string _username;
		protected string _password;
		protected DbList<User_Role> _user_roles;


		public User()
		{
			_userPrimaryKey = new UserPrimaryKey();
			_username = "";
			_password = "";
			_user_roles = null;
		}

		#region IDbObject<UserPrimaryKey> Members

		public UserPrimaryKey Key
		{
			get { return _userPrimaryKey; }
		}

		#endregion

		public string Username
		{
			get { return _username; }
			set
			{
				_username = value;
				_UpdateState();
			}
		}

		public string Password
		{
			get { return _password; }
			set
			{
				_password = value;
				_UpdateState();
			}
		}

		public DbList<User_Role> User_Roles
		{
			get
			{
				if ( _user_roles == null )
				{
					DbUser_Role dbUser_Role;
					if ( !string.IsNullOrEmpty(_ConnectionStringName) )
						dbUser_Role = new DbUser_Role(_ConnectionStringName);
					else
						dbUser_Role = new DbUser_Role();

					_user_roles = dbUser_Role.SelectByUserID(this.Key.UserID);
				}
				return _user_roles;
			}
		}

		public override void Update()
		{
			OnUpdating(this);

			DbUser dbUser = CreateDbUser();
			dbUser.Update(this);

			OnUpdated(this);
		}

		public override void Insert()
		{
			OnInserting(this);

			DbUser dbUser = CreateDbUser();
			dbUser.Insert(this);

			OnInserted(this);
		}

		public override void Delete()
		{
			OnDeleting(this);

			DbUser dbUser = CreateDbUser();
			dbUser.Delete(this);

			OnDeleted(this);
		}

		protected DbUser CreateDbUser()
		{
			if ( !string.IsNullOrEmpty(_ConnectionStringName) )
				return new DbUser(_ConnectionStringName);
			else
				return new DbUser();
		}

		public static User CreateFromReader(IDataReader reader)
		{
			User user = new User();

			FillFromReader(user, reader);

			return user;
		}

		public static void FillFromReader(User user, IDataReader reader)
		{
			user.OnLoading(user);

			user.Key.UserID = (int)reader["UserID"];
			user._username = reader["Username"].ToString();
			user._password = reader["Password"].ToString();

			user._UpdateState(ObjectState.None);

			user.OnLoaded(user);
		}
	}
}
